import requests
import json
import re
from openpyxl import load_workbook
from openpyxl import Workbook
import time
import configparser
import os
import tkinter
import tkinter.messagebox

cookie = ''
filename = 'gaojing.xlsx'


def write(info, man, ftime, endtime):
    xiangxijson = json.loads(info)
    # warningTime = xiangxijson['results']['content']['时间']
    warningTime = ftime
    SN = '*'
    NOC = '*'
    ServerN = xiangxijson['results']['content']['机器名字']
    ip = xiangxijson['results']['content']['IP地址']

    mokuai = xiangxijson['results']['content']['业务分类']
    omp = re.search(r'(?<=/).*?(?=/)', mokuai, re.S | re.M | re.I).group(0)
    db = '*'
    miaoshu = '*'
    log = xiangxijson['results']['content']['简介']

    if re.search(r'磁盘使用', log, re.S | re.M | re.I):
        db = '服务器-磁盘告警'
        miaoshu = '磁盘告警'

    if re.search(r'(cpu idle time|load average|cpu user time)', log, re.S | re.M | re.I):
        db = '服务器-CPU告警'
        miaoshu = 'CPU告警'

    if re.search(r'(丢包率|重启)', log, re.S | re.M | re.I):
        db = '服务器-机器宕机'
        miaoshu = '服务器宕机'

    if re.search(r'(Agent连接不上|文件句柄使用率)', log, re.S | re.M | re.I):
        if re.search(r'(Agent连接不上|文件句柄使用率)', log, re.S | re.M | re.I).group(0) == 'Agent连接不上':
            db = '服务器-机器宕机'
            miaoshu = '服务器宕机'
        if re.search(r'(Agent连接不上|文件句柄使用率)', log, re.S | re.M | re.I).group(0) == '文件句柄使用率':
            db = '业务告警'
            miaoshu = '文件句柄使用率过高'

    if re.search(r'网卡发送流量', log, re.S | re.M | re.I):
        db = '服务器-网卡告警'
        miaoshu = '网卡流量告警'

    if re.search(r'内存使用率', log, re.S | re.M | re.I):
        db = '服务器-内存告警'
        miaoshu = '内存告警'

    wb2 = load_workbook(filename)
    sheet = wb2['Sheet']
    # print(sheet.max_row)
    sheet.append([warningTime, SN, NOC, ServerN, ip, omp, mokuai, db, miaoshu, log, man, endtime])

    try:
        wb2.save(filename)
        print(
            warningTime + '-' + ServerN + '-' + ip + '-' + omp + '-' + mokuai + '-' + db + '-' + miaoshu + '-' + log + '-' + man + '-' + endtime)
    except PermissionError:
        print('文件保存失败')


cf = configparser.ConfigParser()
cf.read("config.ini")
cookie = cf.get("config", "cookie")

headers = {"Content-Language": "en-US", "Cookie": cookie}

response = requests.get(
    "https://shuidi.oppoer.me/oac/noc/mergeItem.do?page=1&pageSize=10000&status=0,1,2&followerId=&appName=&name=&first_hit_time=0&latest_hit_time=&latestEventLevel=CRITICAL&managerUserId=",
    headers=headers)

jsons = json.loads(response.text)
print(jsons)
try:
    os.remove(filename)
    wb2 = Workbook()
    wb2.save(filename)
except PermissionError:
    tkinter.messagebox.showinfo('提示', '记录不能保存需要关闭打开的xlsx文件')

index = 0
for v in jsons['results']:
    gaojingxiang = ['cpu idle time均值', '服务器Agent', '磁盘空间', '机器负载' '机器重启', 'cpu user time均值', 'load average', '内存使用率',
                    '丢包率 = 100%',
                    '重启', '网卡发送流量', '文件句柄使用率']
    index += 1
    for g in gaojingxiang:
        if v['name'] == g:
            # print(v)
            getxiangxi = requests.get(
                "https://shuidi.oppoer.me/oac/noc/latestEvent.do?latestEventId=" + v['latest_event_id'],
                headers=headers)
            # print(getxiangxi.text)
            gengjingreng = '*'
            ftime = '*'
            endtime = '*'

            if v['status_value'] != '未认领':
                gengjingreng = v['operator_user_displayname']
                ftime = v['first_hit_time']
                endtime = v['latest_hit_time']

                write(getxiangxi.text, str(gengjingreng),
                      str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(ftime))),
                      str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(endtime))))
    print(str(index) + ":")
